package io.github.betwowt.web;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserResource {


    private List<User> users = Lists.newArrayList(
            new User("bob", 1),
            new User("andy", 2),
            new User("jany", 3)
    );

    /**
     * @param ids 1,2,3
     * @return
     */
    @GetMapping("/getUsers")
    public ResponseEntity<List<User>> getUser(@RequestParam("ids") String ids) {
        List<String> idList = Splitter.on(",").splitToList(ids);
        for (String e : idList) {
            if (Ints.tryParse(e) == null){
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
            }
        }
        return ResponseEntity.ok(users.stream().
                filter(e->idList.contains(e.getId())).collect(Collectors.toList()));
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Slf4j
    static class User {
        private String name;
        private Integer id;
    }
}
